package com.rongji.dfish.misc.util;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

import com.rongji.dfish.base.util.DateUtil;
import com.rongji.dfish.base.util.LogUtil;
import com.rongji.dfish.base.util.Utils;


/**
 * 导出Excel文件
 *
 * @author CZZ
 */
public class ExportExcel {


    /**
     * Excel 标题
     */
    private String title;


    /**
     * 需要导出的数据
     */
    private List<?> content;


    /**
     * Excel 格式
     * tips: 默认 XLSX
     */
    private String format;


    /**
     * 元素classType
     */
    private Class<?> classType;


    /**
     * 输出流
     */
    private OutputStream outputStream;


    /**
     * 导出的文件名
     */
    private String fileName;


    /**
     * 工作薄对象
     */
    private SXSSFWorkbook wb;


    /**
     * 工作表对象
     */
    private SXSSFSheet sheet;


    /**
     * 样式列表
     */
    private Map<String, CellStyle> styles;


    /**
     * 当前行号
     */
    private int rownum;


    /**
     * 输出流
     */
    private OutputStream target;


    /**
     * 注解列表（Object[]{ ExcelField, Field/Method }）
     */
    private List<Object[]> annotationList = new ArrayList<>();


    /**
     * 数据格式
     */
    private DataFormat dataFormat;


    /**
     * Excel 标题
     */
    public ExportExcel setTitle(String title) {
        this.title = title;
        return this;
    }


    /**
     * 需要导出的数据
     */
    public <E> ExportExcel setContent(List<E> content) {
        this.content = content;
        if (content != null) {
            if (content.size() > 0) {
                this.classType = content.get(0).getClass();
            }
        }
        return this;
    }


    /**
     * Excel 格式
     * tips: 默认 XLSX
     */
    public ExportExcel setFormat(String format) {
        this.format = format;
        return this;
    }


    /**
     * 响应
     */
    public ExportExcel setTarget(HttpServletResponse response) throws IOException {
        this.format = Utils.isEmpty(format) ? ExcelConstants.SUFFIX_XLSX : format;
        this.fileName = Utils.isEmpty(fileName) ? DateUtil.format(new Date(), DateUtil.PATTERN_DATE) : fileName;
        response.reset();
        response.setContentType("application/octet-outputStream; charset=utf-8");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(this.fileName + this.format, "UTF-8"));
        return setTarget(response.getOutputStream());
    }


    public ExportExcel setTarget(OutputStream outputStream) {
        this.outputStream = outputStream;
        return this;
    }


    /**
     * 导出的文件名
     */
    public ExportExcel setFileName(String fileName) {
        this.fileName = fileName;
        return this;
    }


    /**
     * 开始构建Excel
     */
    public void build() throws IOException {
        assert content != null;
        assert outputStream != null;
        assert classType != null;
        //制作表头
        initialize(title);
        //获取数据
        setDataList(content);
        write();
    }


    private void findAnno(ExcelField ef, int[] groups, Object host) {
        if (ef != null && ef.type() != 2) {
            //2为导入专用
            Method getter = null;
            try {
                if (Utils.notEmpty(ef.value())) {
                    getter = classType.getMethod(getterName(ef.value()));
                } else if (host instanceof Field) {
                    getter = classType.getMethod(getterName(((Field) host).getName()));
                } else if (host instanceof Method) {
                    Method method = (Method) host;
                    if (method.getName().startsWith("set")) {
                        String getterName = "g" + method.getName().substring(1);
                        getter = classType.getMethod(getterName);
                    } else {
                        getter = method;
                    }
                }

                if (groups != null && groups.length > 0) {
                    boolean inGroup = false;
                    for (int g : groups) {
                        if (inGroup) {
                            break;
                        }
                        for (int efg : ef.groups()) {
                            if (g == efg) {
                                inGroup = true;
                                annotationList.add(new Object[]{ef, getter});
                                break;
                            }
                        }
                    }
                } else {
                    annotationList.add(new Object[]{ef, getter});
                }
            } catch (NoSuchMethodException e) {
                LogUtil.warn("无法识别属性" + ef.value());
            }
        }
    }

    private String getterName(String filed) {
        char c = filed.charAt(0);
        if (c >= 'a' && c <= 'z') {
            return "get" + (char) (c - 32) + filed.substring(1);
        } else {
            return "get" + filed;
        }
    }

    /**
     * 初始化函数
     *
     * @param title 表格标题，传“空值”，表示无标题
     */
    protected void initialize(String title) {
        int[] groups = new int[]{};

        Field[] fs = classType.getDeclaredFields();
        Field[] superFs = classType.getSuperclass().getDeclaredFields();
        Field[] fields = ArrayUtils.addAll(fs, superFs);
        for (Field f : fields) {
            ExcelField ef = f.getAnnotation(ExcelField.class);
            findAnno(ef, groups, f);
        }
        Method[] ms = classType.getDeclaredMethods();
        Method[] superMs = classType.getSuperclass().getDeclaredMethods();
        Method[] methods = ArrayUtils.addAll(ms, superMs);
        for (Method m : methods) {
            ExcelField ef = m.getAnnotation(ExcelField.class);
            findAnno(ef, groups, m);
        }


        annotationList.sort(Comparator.comparingInt(o -> ((ExcelField) o[0]).order()));

        List<Object[]> headerList = new ArrayList<>();
        for (Object[] os : annotationList) {
            ExcelField excelField = ((ExcelField) os[0]);
            String t = excelField.title();
            int w = excelField.width();
            // 如果是导出，则去掉注释
            String[] ss = StringUtils.split(t, "**", 2);
            if (ss.length == 2) {
                t = ss[0];
            }
            headerList.add(new Object[]{t, w});
        }

        //准备好头信息
        //以下在excel里面绘制表头

        this.wb = new SXSSFWorkbook(500);
        this.sheet = wb.createSheet("Export");
        this.dataFormat = wb.createDataFormat();
        this.styles = createStyles(wb);
        // Create title
        if (Utils.notEmpty(title)) {
            Row titleRow = sheet.createRow(rownum++);
            titleRow.setHeightInPoints(30);
            Cell titleCell = titleRow.createCell(0);
            titleCell.setCellStyle(styles.get("title"));
            titleCell.setCellValue(title);
            sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(),
              titleRow.getRowNum(), titleRow.getRowNum(), headerList.size() - 1));
        }
        // Create header
        Row headerRow = sheet.createRow(rownum++);
        headerRow.setHeightInPoints(16);
        for (int i = 0; i < headerList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellStyle(styles.get("header"));
            Object[] headItem = headerList.get(i);
            String titleVal = headItem[0] == null ? "" : (String) headItem[0];
            String[] ss = StringUtils.split(titleVal, "**", 2);
            if (ss.length == 2) {
                cell.setCellValue(ss[0]);
                Comment comment = this.sheet.createDrawingPatriarch().createCellComment(
                  new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
                comment.setString(new XSSFRichTextString(ss[1]));
                cell.setCellComment(comment);
            } else {
                cell.setCellValue(titleVal);
            }
            sheet.trackAllColumnsForAutoSizing();
            sheet.autoSizeColumn(i);
        }
        for (int i = 0; i < headerList.size(); i++) {
            Object[] headItem = headerList.get(i);
            int w = (Integer) headItem[1];
            if (w > 0) {
                sheet.setColumnWidth(i, w);
            } else {
                sheet.setColumnWidth(i, ExcelConstants.COL_WIDTH_SMALL);
            }

        }

        LogUtil.debug("Initialize success.");
    }


    /**
     * 创建表格样式
     *
     * @param wb 工作薄对象
     * @return 样式列表
     */
    private Map<String, CellStyle> createStyles(Workbook wb) {

        Map<String, CellStyle> styles = new HashMap<>();

        CellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);

        style.setVerticalAlignment(VerticalAlignment.CENTER);
        Font titleFont = wb.createFont();
        titleFont.setFontName("Arial");
        titleFont.setFontHeightInPoints((short) 16);
        titleFont.setBold(true);


        style.setFont(titleFont);
        styles.put("title", style);

        style = wb.createCellStyle();
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderRight(BorderStyle.THIN);
        style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderLeft(BorderStyle.THIN);
        style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderTop(BorderStyle.THIN);
        style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderBottom(BorderStyle.THIN);
        style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        Font dataFont = wb.createFont();
        dataFont.setFontName("Arial");
        dataFont.setFontHeightInPoints((short) 10);
        style.setFont(dataFont);
        styles.put("data", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.LEFT);
        styles.put("data1", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.CENTER);
        styles.put("data2", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.RIGHT);
        styles.put("data3", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.RIGHT);
        style.setDataFormat(this.dataFormat.getFormat("0.0"));
        styles.put("data4", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.RIGHT);
        style.setDataFormat(this.dataFormat.getFormat("0.00"));
        styles.put("data5", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.RIGHT);
        style.setDataFormat(this.dataFormat.getFormat("0.000"));
        styles.put("data6", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.RIGHT);
        style.setDataFormat(this.dataFormat.getFormat("0.0000"));
        styles.put("data7", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setDataFormat(this.dataFormat.getFormat(DateUtil.PATTERN_FULL));
        styles.put("data8", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        Font headerFont = wb.createFont();
        headerFont.setFontName("Arial");
        headerFont.setFontHeightInPoints((short) 10);
        headerFont.setBold(true);
        headerFont.setColor(IndexedColors.WHITE.getIndex());
        style.setFont(headerFont);
        styles.put("header", style);

        return styles;
    }


    /**
     * 添加一行
     *
     * @return 行对象
     */
    private Row addRow() {
        return sheet.createRow(rownum++);
    }


    /**
     * 添加一个单元格
     *
     * @param row    添加的行
     * @param column 添加列号
     * @param val    添加值
     * @return 单元格对象
     */
    public Cell addCell(Row row, int column, Object val) {
        return this.addCell(row, column, val, 0, "", 0, Class.class);
    }


    /**
     * 添加一个单元格
     *
     * @param row    添加的行
     * @param column 添加列号
     * @param val    添加值
     * @param align  对齐方式（1：靠左；2：居中；3：靠右）
     * @return 单元格对象
     */
    public Cell addCell(Row row, int column, Object val, int align, String dateFormat, int precision, Class<?> fieldType) {
        Cell cell = row.createCell(column);
        CellStyle style = styles.get("data" + (align >= 1 && align <= 3 ? align : ""));
        try {
            if (precision > 0) {
                precision = precision > 4 ? 4 : precision;
                style = styles.get(ExcelConstants.STYLE_KEY_MAP.get(precision));
            }
            if (val == null) {
                cell.setCellValue("");
            } else if (val instanceof String) {
                cell.setCellValue((String) val);
            } else if (val instanceof Integer) {
                cell.setCellValue((Integer) val);
            } else if (val instanceof Long) {
                cell.setCellValue((Long) val);
            } else if (val instanceof Double) {
                cell.setCellValue((Double) val);
            } else if (val instanceof Float) {
                cell.setCellValue((Float) val);
            } else if (val instanceof Date) {
                style = styles.get("data8");
                if (Utils.notEmpty(dateFormat)) {
                    style.setDataFormat(this.dataFormat.getFormat(dateFormat));
                }
                cell.setCellValue((Date) val);
            } else {
                if (fieldType != Class.class) {
                    cell.setCellValue((String) fieldType.getMethod("setValue", Object.class).invoke(null, val));
                } else {
                    cell.setCellValue((String) Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
                      "fieldtype." + val.getClass().getSimpleName() + "Type")).getMethod("setValue", Object.class).invoke(null, val));

                }
            }
        } catch (Exception ex) {
            LogUtil.info("Set cell value [" + row.getRowNum() + "," + column + "] error: " + ex.toString());
            cell.setCellValue(val == null ? "" : val.toString());
        }
        cell.setCellStyle(style);
        return cell;
    }


    public ExportExcel setClassType(Class<?> classType) {
        this.classType = classType;
        return this;
    }


    /**
     * 添加数据（通过annotation.ExportField添加数据）
     *
     * @return list 数据列表
     */
    protected <E> ExportExcel setDataList(List<E> list) {

        for (E e : list) {
            int column = 0;
            Row row = this.addRow();
            StringBuilder sb = new StringBuilder();
            for (Object[] os : annotationList) {
                ExcelField ef = (ExcelField) os[0];
                Object val;
                try {
                    Method getter = (Method) os[1];
                    val = getter.invoke(e);
                } catch (Exception ex) {
                    LogUtil.info(ex.toString());
                    val = "";
                }
                this.addCell(row, column++, val, ef.align(), ef.dateFormat(), ef.precision(), ef.fieldType());
                sb.append(val).append(", ");
            }
            LogUtil.debug("Write success: [" + row.getRowNum() + "] " + sb.toString());
        }
        return this;
    }


    /**
     * 输出到客户端
     */
    protected void write() throws IOException {
        wb.write(outputStream);
        outputStream.close();
        wb.dispose();
    }
}
